import { Column, Entity, PrimaryGeneratedColumn, BeforeInsert } from "typeorm";

import { Exclude, Expose } from 'class-transformer';
import * as jwt from 'jsonwebtoken';
import NodeAuth from 'node-auth0';

@Entity("user")
export class UserEntity {
	@Exclude()
	private nodeAuth: NodeAuth;
	constructor () {
		this.nodeAuth = new NodeAuth();
	}

	@PrimaryGeneratedColumn({
		type: "int",
		name: "id"
	})
	id: number;


	@Column('varchar', {
		nullable: false,
		primary: true,
		generated: 'uuid',
		length: 50,
		name: 'uuid',
		comment: 'uuid',
	})
	uuid: string;


	@Column("varchar", {
		nullable: false,
		unique: true,
		length: 50,
		name: "username"
	})
	username: string;

	@Exclude() // 
	@Column("varchar", {
		nullable: false,
		length: 100,
		name: "password"
	})
	password: string;


	@Column("varchar", {
		nullable: true,
		unique: true,
		length: 11,
		name: "mobile"
	})
	mobile: string | null;


	@Column("varchar", {
		nullable: true,
		unique: true,
		length: 50,
		name: "email"
	})
	email: string | null;


	@Column("tinyint", {
		nullable: true,
		default: () => "'1'",
		name: "status"
	})
	status: number | null;


	@Column("varchar", {
		nullable: true,
		length: 50,
		name: "platform"
	})
	platform: string | null;


	@Column("tinyint", {
		nullable: false,
		default: () => "'0'",
		name: "is_super"
	})
	isSuper: number;


	@Column("timestamp", {
		nullable: false,
		default: () => "CURRENT_TIMESTAMP",
		name: "created_at"
	})
	createdAt: Date;


	@Column("timestamp", {
		nullable: false,
		default: () => "CURRENT_TIMESTAMP",
		name: "updated_at"
	})
	updatedAt: Date;

	@Expose() // 表示根据现有的字段生成一个新的字段
	// eslint-disable-next-line @typescript-eslint/camelcase
	get is_active(): string {
		return this.status ? '有效' : '无效';
	}

	@BeforeInsert()
	makePassword() {
		this.password = this.nodeAuth.makePassword(this.password);
	}


	@Expose()
	private get token() {
		const { id, uuid, username, mobile, email, isSuper } = this;
		// 生成签名
		return jwt.sign(
			{
				id,
				uuid,
				username,
				mobile,
				email,
				isSuper,
			},
			process.env.SECRET, // 加盐
			{
				expiresIn: '7d', // 过期时间
			},
		);
	}

  /**
   * @Author: 水痕
   * @Date: 2020-01-23 09:19:49
   * @LastEditors: 水痕
   * @Description: 定义返回数据,用了这个函数后上面的Exclude和Expose就失效了
   * @param {type} 
   * @return: 
   */
	public toResponseObject(isShowToken = true): object {
		// eslint-disable-next-line @typescript-eslint/no-unused-vars
		const { nodeAuth, password, token, ...params } = this;
		if (isShowToken) {
			return {
				token,
				...params,
			};
		} else {
			return {
				...params,
			};
		}
	}
}	
